package com.cspg.ssss.service;

import com.alibaba.fastjson.JSONObject;
import com.cspg.ssss.domain.*;
import com.cspg.ssss.repository.DaiBanMapper;
import com.cspg.ssss.repository.SafeDeptMapMapper;
import com.cspg.ssss.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DaiBanService {
    @Autowired
    DaiBanMapper daiBanMapper;
    @Autowired
    CheckBatchService checkBatchService;
    @Autowired
    ObjHistoryService objHistoryService;
    @Autowired
    SafeDeptMapMapper safeDeptMapMapper;

    public List<BacklogEntity> selectdb(Map<String, Object> map) {
        return daiBanMapper.selectdb(map);
    }

    //查询经办列表
    public List<BackHaveEntity> selectHandlingList(Map<String, Object> map) {
        return daiBanMapper.selectHandlingList(map);
    }

    //查询发起列表
    public List<BackHaveEntity> selectLaunchList(Map<String, Object> map) {
        List<BackHaveEntity> list = daiBanMapper.selectLaunchList(map);
        for (BackHaveEntity entity : list) {
            if (entity.getOpList() != null && entity.getOpList().size() != 0) {
                entity.setUserName(entity.getOpList().get(0).get("userName"));
                entity.setCreateTime(entity.getOpList().get(0).get("createTime"));
                entity.setOpList(null);
            }
        }
        return list;
    }

    public void insertBacklog(BacklogEntity updateBacklog) {
        daiBanMapper.insertBacklog(updateBacklog);
    }

    public int updateBacklog(BacklogEntity entity) {
        return daiBanMapper.updateBacklog(entity);
    }

    public void deleteBacklog(Integer id) {
        List<Integer> idList = new ArrayList<>();
        idList.add(id);
        daiBanMapper.deleteBacklogByList(idList);
    }

    public void deleteBacklogByProblemId(String problemId) {
        daiBanMapper.deleteBacklogByProblemId(problemId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateBacklogList(int check_type) throws ParseException {
        List<Integer> idList = new ArrayList<>();
        //查询待办表里的数据
        Map<String, Object> map = new HashMap<>();
        map.put("check_type", check_type + "");
        List<BacklogEntity> oldList = daiBanMapper.selectdb(map);
        for (BacklogEntity entity : oldList) {
            idList.add(entity.getId());
        }
        CheckBatchInst inst = checkBatchService.getCurrentCheckBachInst(check_type);
        if (inst != null) {
            JSONObject configObj = JSONObject.parseObject(inst.getConfig());
            int grade_days = configObj.getIntValue("grade");
            int feedback_days = configObj.getIntValue("feedback");
            int review_days = configObj.getIntValue("review");
            int add_score_apply_days = configObj.getIntValue("add_score_apply");
            int add_score_review_days = configObj.getIntValue("add_score_review");
            Date today = DateUtil.getCurrentDate();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            int period = DateUtil.workDaysPeriod(inst.getUpdate_time(), today);

            //查询将插入待办表的打分记录数据
            Map<String, Object> condition = new HashMap<>();
            condition.put("batch_id", inst.getId());
            if (inst.getCheck_type() == 0) {
                condition.put("grade_table", "gsdgdw_grade_view");
            }
            if (inst.getCheck_type() == 1) {
                condition.put("grade_table", "dwdgbm_grade_view");
            }
            List<BacklogEntity> gradeList = daiBanMapper.selectGradeUsers(condition);
            //打分记录数据整合
            for (BacklogEntity grade : gradeList) {
                gradeTerm(grade, sdf, today, period, grade_days, feedback_days, review_days);
                grade.setCheck_type(check_type + "");
                grade.setScore_type("0");
                if (grade.getManList() != null && grade.getManList().size() > 0) {
                    StringBuilder ids = new StringBuilder();
                    String bmmc = "";
                    for (Map<String, String> data : grade.getManList()) {
                        if (grade.getDbstatus().equals("1") && data.get("approve_type").equals("0")) {
                            // 打分审核人员
                            ids.append(";").append(data.get("dbman"));
                            bmmc = data.get("bmmc");
                        } else if (grade.getDbstatus().equals("3") && data.get("approve_type").equals("1")) {
                            // 反馈审核人员
                            ids.append(";").append(data.get("dbman"));
                            bmmc = data.get("bmmc");
                        } else if (grade.getDbstatus().equals("5") && data.get("approve_type").equals("2")) {
                            // 反馈终审人员
                            ids.append(";").append(data.get("dbman"));
                            bmmc = data.get("bmmc");
                        } else if (grade.getDbstatus().equals("4") && data.get("approve_type").equals("5")) {
                            // 反馈复审人员
                            ids.append(";").append(data.get("dbman"));
                            bmmc = data.get("bmmc");
                        }
                    }
                    if (ids.length() > 0)
                        grade.setDbman(ids.toString());
                    grade.setBmmc(bmmc);
                }
                if (StringUtils.isEmpty(grade.getBmmc())) {
                    grade.setBmmc("超高压输电公司/" + grade.getKhbm().replace("->", "/"));
                }
                if ("2".equals(grade.getDbstatus())) {
                    grade.setBmmc("超高压输电公司/" + grade.getProblem_bmmc().replace("->", "/"));
                    grade.setDbman("-1");
                }
                grade.setBmmc(grade.getBmmc().replaceAll("超高压输电公司/超高压输电公司/","超高压输电公司/"));
                grade.setType("0");
                boolean con = true; //用于判断待办表里是否有gradeList的数据
                for (BacklogEntity db : oldList) {
                    if (grade.getProblem_id().equals(db.getProblem_id())
                            && grade.getType().equals(db.getType())) {
                        idList.remove(db.getId());
                        if (!grade.getTerm().equals(db.getTerm())
                                || !grade.getDbstatus().equals(db.getDbstatus())) {
                            //当整改问题id相同时，更新待办表数据
                            BacklogEntity update = new BacklogEntity();
                            update.setId(db.getId());
                            update.setTerm(grade.getTerm());
                            update.setDbstatus(grade.getDbstatus());
                            update.setDbman(grade.getDbman());
                            update.setBmmc(grade.getBmmc());
                            daiBanMapper.updateBacklog(update);
                        }
                        con = false;
                        break;
                    }
                }
                if (con) {
                    grade.setCreattime(new Date());
                    //待办表里没有gradeList的数据,插入数据
                    daiBanMapper.insertBacklog(grade);
                }
            }
            //查询将插入待办表的加分申请数据
            condition.put("apply_type", check_type);
            List<BacklogEntity> scoreList = daiBanMapper.selectScoreApplyUsers(condition);
            //加分申请数据整合
            for (BacklogEntity score : scoreList) {
                scoreTerm(score, sdf, today, period, add_score_apply_days, add_score_review_days);
                if (score.getManList() != null && score.getManList().size() > 0) {
                    StringBuilder ids = new StringBuilder();
                    String bmmc = "";
                    for (Map<String, String> data : score.getManList()) {
                        if (score.getDbstatus().equals("0") && data.get("approve_type").equals("3")) {
                            // 打分审核人员
                            ids.append(";").append(data.get("dbman"));
                            bmmc = data.get("bmmc");
                        } else if (score.getDbstatus().equals("3") && data.get("approve_type").equals("6")) {
                            // 反馈审核人员
                            ids.append(";").append(data.get("dbman"));
                            bmmc = data.get("bmmc");
                        } else if (score.getDbstatus().equals("1") && data.get("approve_type").equals("4")) {
                            // 反馈终审人员
                            ids.append(";").append(data.get("dbman"));
                            bmmc = data.get("bmmc");
                        }
                    }
                    if (ids.length() > 0)
                        score.setDbman(ids.toString());
                    score.setBmmc(bmmc);
                }
                if (score.getDbstatus().equals("4")) {
                    score.setDbman("-1");
                    score.setBmmc(score.getProblem_bmmc());
                }
                score.setCheck_type(check_type + "");
                score.setScore_type("1");
                score.setType("0");
                boolean con = true; //用于判断待办表里是否有scoreList的数据
                for (BacklogEntity db : oldList) {
                    if (score.getProblem_id().equals(db.getProblem_id())
                            && score.getType().equals(db.getType())) {
                        idList.remove(db.getId());
                        //当加分申请id相同时，更新待办表数据
                        if (!score.getTerm().equals(db.getTerm())
                                || !score.getDbstatus().equals(db.getDbstatus())) {
                            BacklogEntity update = new BacklogEntity();
                            update.setId(db.getId());
                            update.setTerm(score.getTerm());
                            update.setDbstatus(score.getDbstatus());
                            update.setDbman(score.getDbman());
                            update.setBmmc(score.getBmmc());
                            daiBanMapper.updateBacklog(update);
                        }
                        con = false;
                        break;
                    }
                }
                if (con) {
                    score.setCreattime(new Date());
                    //待办表里没有scoreList的数据,插入数据
                    daiBanMapper.insertBacklog(score);
                }
            }
        }
        //问题整改
        List<BacklogEntity> problemList = daiBanMapper.selectProblemUsers(check_type);
        String dayStr = DateUtil.getCurrentDateStr();
        for (BacklogEntity problem : problemList) {
            int days = 0;
            if (!StringUtils.isEmpty(problem.getWtfxsj())) {
                days = DateUtil.workDays(problem.getWtfxsj(), dayStr);
            }
            if (days < 7) {
                problem.setTerm("0");
            } else if (days > 15) {
                problem.setTerm("2");
            } else {
                problem.setTerm("1");
            }
            if (problem.getDbstatus() == null) {
                problem.setDbstatus("0");
            }
            switch (problem.getDbstatus()) {
                case "duty":
                    problem.setDbstatus("1");
                    break;
                case "rectify":
                    if (problem.getFlow_type().equals("0")) {
                        problem.setDbstatus("2");
                        if(check_type == 1){
                            problem.setBmmc(getSafeDeptPath(problem.getBmmc()));
                        }
                    }else {
                        problem.setDbstatus("5");
                    }
                    break;
                case "approve":
                    problem.setDbstatus(problem.getFlow_type().equals("0")?"3":"7");
                    break;
                case "commit":
                    if (problem.getFlow_type().equals("0")) {
                        problem.setDbstatus("4");
                        if(check_type == 1){
                            problem.setBmmc(getSafeDeptPath(problem.getBmmc()));
                        }
                    }else {
                        problem.setDbstatus("8");
                    }
                    break;
                case "manage_approve":
                    problem.setDbstatus("6");
                    if(check_type == 1){
                        problem.setBmmc(getSafeDeptPath(problem.getBmmc()));
                    }
                    break;
                case "review_approve":
                    problem.setDbstatus("7");
                    break;
                case "manage_complete":
                    problem.setDbstatus("9");
                    if(check_type == 1){
                        problem.setBmmc(getSafeDeptPath(problem.getBmmc()));
                    }
                    break;
                default:
                    problem.setDbstatus("0");
                    if(check_type == 1){
                        problem.setBmmc(getSafeDeptPath(problem.getBmmc()));
                    }
                    break;
            }
            problem.setCheck_type(check_type + "");
            problem.setType("1");
            boolean con = true; //用于判断待办表里是否有scoreList的数据
            for (BacklogEntity db : oldList) {
                if (problem.getProblem_id().equals(db.getProblem_id())
                        && problem.getType().equals(db.getType())) {
                    idList.remove(db.getId());
                    if (!problem.getTerm().equals(db.getTerm())
                            || !problem.getDbstatus().equals(db.getDbstatus())
                            || !problem.getBmmc().equals(db.getBmmc())) {
                        //当加分申请id相同时，更新待办表数据
                        BacklogEntity update = new BacklogEntity();
                        update.setId(db.getId());
                        update.setTerm(problem.getTerm());
                        update.setDbstatus(problem.getDbstatus());
                        update.setBmmc(problem.getBmmc());
                        daiBanMapper.updateBacklog(update);
                    }
                    con = false;
                    break;
                }
            }
            if (con) {
                problem.setCreattime(new Date());
                //待办表里没有problemList的数据,插入数据
                daiBanMapper.insertBacklog(problem);
            }
        }
        if (idList.size() > 0)
            daiBanMapper.deleteBacklogByList(idList);
    }

    private String getUserCompany(String userdept) {
        String[] arrPath = userdept.split("->");
        if (arrPath.length >= 2 && arrPath[1].equals("海口分局")) {
            return arrPath[0] + "/" + arrPath[1];
        }
        return arrPath[0];
    }

    private String getSafeDeptPath(String userdept) {
        String CompanyPath = getUserCompany(userdept);
        if (!CompanyPath.equals("")) {
            List<SafeDeptMap> ls = safeDeptMapMapper.selectDeptNameForCompany(CompanyPath);
            if (ls != null && ls.size() == 1) {
                return "超高压输电公司/" + ls.get(0).getCompany() + "/" + ls.get(0).getSafe_dept();
            }
        }
        return "";
    }

    //打分记录的期限判断
    private void gradeTerm(BacklogEntity grade, SimpleDateFormat sdf, Date today, int period, int grade_days, int feedback_days, int review_days) throws ParseException {
        Map<String, Object> scoreMap = new HashMap<>();
        scoreMap.put("obj_id", grade.getProblem_id());
        scoreMap.put("obj_type", 0);
        List<ObjHistoryEntity> historyList = objHistoryService.getObjectHistory(scoreMap);
        Calendar calendar = Calendar.getInstance();
        int days;
        if (historyList != null && historyList.size() > 0) {
            ObjHistoryEntity history = historyList.get(0);
            calendar.setTime(history.getCreate_time());
            if (history.getOp_event().equals("save") || history.getOp_event().equals("grade")) {
                days = grade_days;
            } else if (history.getOp_event().equals("check") || history.getOp_event().equals("feedback") || history.getOp_event().equals("approve")) {
                days = grade_days + feedback_days;
            } else {
                days = grade_days + feedback_days + review_days;
            }
        } else {
            Date startDate = sdf.parse(grade.getWtfxsj());
            calendar.setTime(startDate);
            days = grade_days;
        }
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        if (days - period < 0) {
            grade.setTerm("2");
        } else if (DateUtil.workDaysPeriod(calendar.getTime(), today) >= 7) {
            grade.setTerm("1");
        } else {
            grade.setTerm("0");
        }
    }


    //加分申请的期限判断
    private void scoreTerm(BacklogEntity score, SimpleDateFormat sdf, Date today, int period, int add_score_apply_days, int add_score_review_days) throws ParseException {
        Map<String, Object> scoreMap = new HashMap<>();
        scoreMap.put("obj_id", score.getProblem_id());
        scoreMap.put("obj_type", 1);
        List<ObjHistoryEntity> historyList = objHistoryService.getObjectHistory(scoreMap);
        Calendar calendar = Calendar.getInstance();
        int days;
        if (historyList != null && historyList.size() > 0) {
            ObjHistoryEntity history = historyList.get(0);
            calendar.setTime(history.getCreate_time());
            if ("0".equals(score.getDbstatus())) {
                days = add_score_apply_days;
            } else {
                days = add_score_apply_days + add_score_review_days;
            }
        } else {
            Date startDate = sdf.parse(score.getWtfxsj());
            calendar.setTime(startDate);
            days = add_score_apply_days;
        }
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        if (days - period < 0) {
            score.setTerm("2");
        } else if (DateUtil.workDaysPeriod(calendar.getTime(), today) >= 7) {
            score.setTerm("1");
        } else {
            score.setTerm("0");
        }
    }

    public void updateBacklogByGradeDept(Map<String, Object> daibanUpdate) {
        daiBanMapper.updateBacklogByGradeDept(daibanUpdate);
    }
}
